<?php defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * @author chaituan@126.com
 */
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
class Tourism extends WechatCommon {
	
	function detail() {
		$data['id'] = $id = Gets('id','num');//主活动ID
		$this->load->model(array('admin/Tourism_model','admin/TourismChild_model'));
		//获取时间
		$gotime = $this->TourismChild_model->getItems(array('tid'=>$id),'','stime');//当前所有时间数据
		if(!$gotime)showmessage('数据错误','error');
		$seleted = 0;
		$data['init'] = array();
		foreach ($gotime as $k=>$v){
			$v['state'] = 0;
			if($v['etime']){
				$v['times'] = date('m/d',strtotime($v['stime'])).' ~ '.date('m/d',strtotime($v['etime']));
			}else{
				$v['times'] = date('m/d',strtotime($v['stime']));
			}
			if(strtotime($v['stime']) > time()){ 
				if(!$seleted){
					$seleted++;
					$data['init'] = array('selected_init'=>$k,'init_cid'=>$v['id'],'state'=>$v['state']);
					$v['selected'] = 'selected';
				}
				if($v['sign_num'] < $v['in_line']){
					$v['state_html'] = '<span class="cr-signup">火热报名中</span>';
				}elseif($v['sign_num'] < $v['full']&&$v['sign_num'] >= $v['in_line']){
					$v['state_html'] = '<span class="cr-alreadygo">已成行</span>';
				}elseif($v['sign_num'] >= $v['full']){
					$v['state_html'] = '<span class="cr-full">已满员</span>';
					$v['state'] = 1;
				} 
			}else{ 
				$v['state_html'] = '<span class="cr-full">活动结束</span>'; 
				$v['state'] = 2;
			}
			$gotime_news[] = $v;
		}
		if(!$data['init'])showmessage('此活动已全部结束','info');
		$data['gotime'] = $gotime_news;
		$tourism = $this->Tourism_model->getItem(array('id'=>$id),'s_title,title,s_thumb,thumb,s_desc');
		$fx = '?fxid='.$this->User['id'];
		$this->load->vars('share_data',array('title'=>$tourism['s_title']?$tourism['s_title']:$tourism['title'],'img'=>base_url($tourism['s_thumb']?$tourism['s_thumb']:$tourism['thumb']),'desc'=>$tourism['s_desc']?$tourism['s_desc']:$tourism['title'],'link'=>base_url('mobile/tourism/detail/id-'.$id.$fx)));
		$this->load->view('mobile/tourism/detail',$data);
	}
	
	function detail_user(){//获取所有报名人信息
		$id = Gets('id','num');
		$this->load->model(array('admin/TourismVirtual_model','admin/TourismChild_model','admin/TourismOrder_model'));
		$data['item'] = $this->TourismChild_model->getItem(array('id'=>$id),'leader');
		
		$orders = $this->TourismOrder_model->getItems(array('tcid'=>$id),'thumb,uid,nickname,info');
		$orders_num = count($orders);
		$orders_new = array();
		if($orders){
			foreach ($orders as $v){
				$v['num'] = count(json_decode($v['info'],true));
				unset($v['info']);
				$orders_new[] = $v;
			}
		}
		$virtual = $this->TourismVirtual_model->getItems(array('tcid'=>$id),'thumb,nickname,num');
		$o_v = array_merge($orders_new,$virtual);
		$data['items'] = $o_v;
		$this->load->view('mobile/tourism/detail_user',$data);
	}
	
	function order(){//开始报名
		$uid = $this->User['id'];
		$cid = $data['cid'] = Gets('cid','num')?Gets('cid','num'):0;//子活动ID
		$id = $data['id'] = Gets('id','num');//主活动id
		$this->load->model(array('admin/Tourism_model','admin/TourismChild_model','admin/Info_model','admin/User_model','admin/Protocol_model'));
		//出发时间 --- 是否已满
		if($cid){//当子活动为空的时候，代表用户是自己创建的活动
			$child = $this->TourismChild_model->getItem(array('id'=>$cid));
			if($child['sign_num'] >= $child['full'])showmessage('报名人数已经满了','error');
		}
		//活动
		$data['item'] = $item = $this->Tourism_model->getItem(array('id'=>$id),'gid,money,exchange');
		
		
		//需要加一个积分 怕有缓存
		$user = $this->User_model->getItem(array('id'=>$uid),'integral');
		$data['integral'] = $user['integral'];
		//常用联系人
		$data['info'] = $this->Info_model->getItem(array('id'=>$this->User['i_id']));
		
		$data['protocol'] = $this->Protocol_model->getItem();
		
		$this->load->view('mobile/tourism/order',$data);
	}
	
	function pay(){
		if(is_ajax_request()){
// 			$agreement = Posts('agreement');//同意旅游服务协议
// 			if(!$agreement)AjaxResult_error("请选择同意旅游服务协议");
			$uid = $this->User['id'];
			$this->load->model(array('admin/TourismChild_model','admin/Tourism_model','admin/TourismGoods_model','admin/User_model','admin/Integral_model','admin/TourismOrder_model'));
			$id = Posts('id','num');//父id
			$cid = Posts('cid','num');//子id
			$item = $this->Tourism_model->getItem(array('id'=>$id),'thumb,title,money,exchange,fx_money');//获取主活动数据
			$money = $item['money'];
			
			$info = Posts('info');//联系人
			$info_money = $money * count(json_decode($info,true));
			if($cid){
				$child = $this->TourismChild_model->getItem(array('id'=>$cid),'etime,stime');
			}else{
				$child = $this->session->child_time;
				if(!$child)AjaxResult_error('数据异常，请返回首页');
			}
			
			$order_no = order_trade_no();
			$data = array('uid'=>$uid,'nickname'=>$this->User['nickname'],'thumb'=>$this->User['thumb'],'tcid'=>$cid,'stime'=>$child['stime'],'etime'=>$child['etime'],'title'=>$item['title'],'tid'=>$id,'oid'=>$order_no,'state'=>1,'g_thumb'=>$item['thumb'],'fx_money'=>$item['fx_money'],'addtime'=>time());
			$data['info'] = $info;
			$goods = isset($_POST['goods'])?$_POST['goods']:'';//商品
			$gnum = '';
			if($goods){
				$goods = json_decode($goods,true);
				foreach ($goods as $v){
					$gid[] = $v['id'];
					$gnum[$v['id']] = $v['num'];
				}
			}
			$goods_money = 0;
			if($gnum){
				$gid = implode(',', $gid);
				$goodsItems = $this->TourismGoods_model->getItems("id in ($gid)");
				foreach ($goodsItems as $v){
					$v['num'] = $gnum[$v['id']];
					$goods_money += $v['tgsmoney'] * $v['num'];
					$goodsNews[] = $v;
				}
				$data['tgs_goods'] = json_encode($goodsNews);
			}
			
			$integral = Posts('integral');//积分,
			$integral_money = 0;
			$user = $this->User_model->getItem(array('id'=>$uid),'integral');
			if($integral&&$integral <= $user['integral']){
				$integral_money = $integral * $item['exchange'];
			}
			$data['integral'] = $integral;
			$data['money'] = $item['money'];
			$data['total'] = $info_money + $goods_money - $integral_money;
			$rid = $this->TourismOrder_model->add($data);
			if($rid){
				//获取微信支付基础配置
				$options = ['app_id'=>WX_APPID,'secret'=>WX_APPSecret,'payment' => ['merchant_id'=> WX_MCHID,'key'=> WX_KEY,'cert_path'=> SSLCERT_PATH,'key_path'=> SSLKEY_PATH,'notify_url'=> NOTIFY_URL]];
				$app = new Application($options);
				$payment = $app->payment;
				//订单参数
				$attributes = ['trade_type'=>'JSAPI','body'=> $item['title'],'detail'=> $item['title'],
				'out_trade_no'=>$order_no,'total_fee'=> $data['total']*100,'notify_url'=> NOTIFY_URL,'openid'=> $this->User['openid']];
				$order = new Order($attributes);
				$result = $payment->prepare($order);//下单接口
				if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
					$prepayId = $result->prepay_id;
					$arr = $payment->configForPayment($prepayId,false);
					AjaxResult(1,'', $arr);
				}else{
					AjaxResult_error("支付接口异常");
				}
				
			}else{
				AjaxResult_error("支付异常0001");
			}
		}
	}
	//活动报名列表 1未支付 '2'=>'已报名','3'=>'已结束','4'=>'已退出','5'=>'申请退出'
	function my_order(){
		if(is_ajax_request()){
			$id = Posts('id','num');
			$where = "and state<>1";
			$state = array(1,2,3,4);
			if($id){
				$id = $state[$id];
				if($id==4){
					$where = "and state in (4,5)";
				}else{
					$where = "and state=$id";
				}
			}
			$uid = $this->User['id'];
			$this->load->model(array('admin/TourismOrder_model'));
			$items = $this->TourismOrder_model->getItems("uid=$uid $where","", 'id desc');
			if($items){
				AjaxResult(1, '',$items);
			}else {
				AjaxResult_error();
			}
		}else{
			$data['id'] = Gets('id','num')?Gets('id','num'):0;
			$this->load->view('mobile/tourism/my_order',$data);
		}
		
	}
	
	function my_odetail(){
		$id = Gets('id','num');
		$uid = $this->User['id'];
		$this->load->model(array('admin/TourismOrder_model'));
		$data['newItems'] = $this->TourismOrder_model->getItem("uid=$uid and id=$id");
		$this->load->view('mobile/tourism/my_detail',$data);
	}
	
	function back(){
		$id = Gets('id','num');
		$uid = $this->User['id'];
		$this->load->model(array('admin/TourismOrder_model'));
		$result = $this->TourismOrder_model->updates(array('state'=>5),"id=$id and uid=$uid and state=2");
		is_AjaxResult($result);
	}
	
	function get_tvenue(){
		$id = Gets('id');
		$tvenue = get_Cache('tourism_venue');
		$news = '';
		foreach ($tvenue as $v){
			if($v['parent_id'] == $id){
				$news[] = $v;
			}
		}
		if($news){
			AjaxResult(1, 'ok',$news);
		}else{
			AjaxResult_error('没有数据');
		}
	}
	
	function search(){
		$key = Gets('key');$lid = $this->User['location'];
		$time = format_time(time(),'Y-m-d');
		$this->load->model(array('admin/Tourism_model'=>'do'));
		$table = array('ct_tourism_child as b'=>"tourism.id=b.tid+left");
		$fields = 'tourism.id,tourism.thumb,tourism.title,b.leader,tourism.diff,tourism.day_num,b.stime,b.leader';
		$where = "tourism.lid = $lid and b.state=1 and (b.stime>'$time' or b.etime>'$time')";
		if($key){
			$where .= " and tourism.title like '%$key%'";
		}
		$result = $this->do->getItems_join($table,$where,$fields,'tourism.sort asc,tourism.id desc');
		$news = '';
		$diff = get_diff();
		foreach ($result as $v){
			$v['diff_say'] = $diff[$v['diff']];//难度解析
			$v['stime'] = format_time(strtotime($v['stime']),'m月d日');
			$v['leader'] = json_decode($v['leader'],true)[0];
			$news[] = $v;
		}
		$data['items'] = json_encode($news);
		$this->load->view('mobile/tourism/search',$data);
	}
}
